/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.sgf.utils.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description
 * @Author Kaixuan Shi
 * @Date 2021/12/8
 * @Version 1.0
 */
public class ThreadPoolManager {

    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolManager.class);
    private final ThreadPoolExecutor threadPool;
    private final String THREAD_NAME_PREFIX = "eapi-thread-";

    public ThreadPoolManager() {
        int maximumPoolSize = 8;
        try {
            int availableProcessors = Runtime.getRuntime().availableProcessors();
            maximumPoolSize = 2 * availableProcessors + 1;
        } catch (Exception e) {
            logger.info("get the number of processors available to the Java virtual machine error,maximumPoolSize:8");
        }
        //保证corePoolSize>=maximumPoolSize,否则抛异常
        maximumPoolSize = Math.max(maximumPoolSize, 8);

        threadPool = new ThreadPoolExecutor(4, maximumPoolSize, 10, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(4),
                new ThreadFactory() {
                    private final AtomicInteger id = new AtomicInteger(0);

                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        thread.setName(THREAD_NAME_PREFIX + id.addAndGet(1));
                        return thread;
                    }
                }, new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

    public void submit(Runnable task) {
        threadPool.submit(task);
    }

    public void shutdown() {
        threadPool.shutdown();
    }

    public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
        return threadPool.awaitTermination(timeout, unit);
    }
}
















